//安装依赖 xlsx  file-saver xlsx-style
//如果cnpm安装报错
//xlsx-style的bug修复:node_module/xlsx-style/dist/cpexcel.js的807行的var cpt = require('./cpt' + 'able')改为var cpt = cptable;
import FileSaver from 'file-saver'
import XLSX from 'xlsx-style';
import XLSX2 from 'xlsx';

function datenum(v, date1904) {
    if (date1904) v += 1462;
    var epoch = Date.parse(v);
    return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
}

// 设置表格中cell默认的字体，居中，颜色等
let defaultCellStyle = {
    font: { name: "宋体", sz: 12, bold: false, color: { auto: 1 } },
    border: {
        color: { sz: 1, auto: 1 }
    },
    alignment: {
        /// 自动换行
        wrapText: 1,
        // 居中
        horizontal: "center",
        vertical: "center",
        indent: 0
    }
}

//从json转化为sheet，xslx中没有aoaToSheet的方法，该方法摘自官方test
function sheet_from_array_of_arrays(data, opts) {
    var ws = {};
    var range = {
        s: {
            c: 10000000,
            r: 10000000
        },
        e: {
            c: 0,
            r: 0
        }
    };
    for (var R = 0; R != data.length; ++R) {
        for (var C = 0; C != data[R].length; ++C) {
            if (range.s.r > R) range.s.r = R;
            if (range.s.c > C) range.s.c = C;
            if (range.e.r < R) range.e.r = R;
            if (range.e.c < C) range.e.c = C;
            var cell = {
                v: data[R][C]
            };
            if (cell.v == null) continue;
            var cell_ref = XLSX.utils.encode_cell({
                c: C,
                r: R
            });

            if (typeof cell.v === 'number') cell.t = 'n';
            else if (typeof cell.v === 'boolean') cell.t = 'b';
            else if (cell.v instanceof Date) {
                cell.t = 'n';
                cell.z = XLSX.SSF._table[14];
                cell.v = datenum(cell.v);
            } else cell.t = 's';

            ws[cell_ref] = cell;
        }
    }
    if (range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range);
    return ws;
}

function Workbook() {
    if (!(this instanceof Workbook)) return new Workbook();
    this.SheetNames = [];
    this.Sheets = {};
}

function s2ab(s) {
    var buf = new ArrayBuffer(s.length);
    var view = new Uint8Array(buf);
    for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
    return buf;
}



// 辅助导出表格的函数
function formatJson(filterVal, jsonData) {
    return jsonData.map(v =>
        filterVal.map(j => {
            if (j === "timestamp") {
                return parseTime(v[j]);
            } else {
                return v[j];
            }
        })
    );
}

function getTreeIds(idList, header, parent) {
    // var idList = []
    for (let child of parent) {
        var keys
        var datas = {}
        for (let index = 0; index < header.length; index++) {
            // const element = array[index];
            keys = header[index]
            datas[keys] = child.classDO[keys]
        }
        idList.push(datas);
        
        if (child.hasChildren) {
            getTreeIds(idList, header, child.children);
        }
    }
    return idList
}
// 辅助导出表格的函数
function treeformatJson(filterVal, jsonData) {
    var idList = []
    idList = getTreeIds(idList, filterVal, jsonData)
    return idList.map(v =>
        filterVal.map(j => {
            if (j === "timestamp") {
                return parseTime(v[j]);
            } else {
                return v[j];
            }
        })
    );
}

/**
 *通过table标签渲染导出表格
 *  by lsw  
 * @export
 * @param {*} [{
 *     id,表格的id
 *     filename,导出的表格名称
 *     bookType = 'xlsx',表格的类型
 *     styleFun ，自定义样式，基于表格ws对象，高度开放样式设定，具体设定方法参考xlsx-style
 * 
 */
export function export_table_to_excel({
    id,
    filename,
    bookType = 'xlsx',
    styleFun
} = {}) {
    var table = document.getElementById(id);
    var ws = XLSX2.utils.table_to_sheet(table);
    styleFun(ws);
    var wb = XLSX2.utils.book_new();
    XLSX2.utils.book_append_sheet(wb, ws, "SheetJS");
    var wbout = XLSX.write(wb, {
        bookType: bookType,
        bookSST: false,
        type: 'binary',
        defaultCellStyle: defaultCellStyle
    });
    FileSaver.saveAs(new Blob([s2ab(wbout)], { type: "" }), filename + "." + bookType)
}

//通过json渲染导出表格

/**
 * by  lsw  用于一定程度上的表格数据导出和样式设定，此方法未开放全部样式设定接口，如果需要请自行修改对应方法
 * @export
 * @param {*} [{
 *     multiHeader = [],//表格的标题，结合合并单元统一使用
 *     header,     表格的头部
 *     filterVal,  表格数据主键--和header汉字一一对应
 *     jsonData,   表格数据
 *     filename,   导出的文件名
 *     merges = [],//要合并的单元格  例如 ['A1:K1','A2:K2']; // 合并单元格
 *     autoWidth = false,  //设置统一的宽度，如果不设置，默认自适应
 *     bookType = 'xlsx' 导出数据的格式
 * 
 */
export function export_json_to_excel({
    multiHeader = [],
    header,
    filterVal,
    jsonData,
    filename,
    merges = [],
    autoWidth = false,
    bookType = 'xlsx',
    type
} = {}) {
    
    /* original data */
    filename = filename || 'excel-list'
    let data
    if (type == "tree") {
        data = treeformatJson(filterVal, jsonData);
    } else {
        data = formatJson(filterVal, jsonData);
    }

    data = [...data]
    data.unshift(header);

    for (let i = multiHeader.length - 1; i > -1; i--) {
        data.unshift(multiHeader[i])
    }

    var ws_name = "SheetJS";
    var wb = new Workbook(),
        ws = sheet_from_array_of_arrays(data);

    // 自定义样式--表头默认加粗
    for (let item in ws) {
        if (item.substring(1, 2) == 1 && item.length == 2) {
            ws[item].s = {
                font: {
                    sz: 13,
                    bold: true,
                },
                alignment: {
                    horizontal: "center",
                    vertical: "center",
                },
            };

        } else if (item != "!merges" && item != "!ref") {
            ws[item].s = {
                font: {
                    sz: 12,
                    bold: false,
                },
                alignment: {
                    horizontal: "center",
                    vertical: "center",
                },
            };
        }
    }


    //合并单元格
    if (merges.length > 0) {
        if (!ws['!merges']) ws['!merges'] = [];
        merges.forEach(item => {
            ws['!merges'].push(XLSX.utils.decode_range(item))
        })
    }

    //设置宽度
    if (!autoWidth) {
        /*设置worksheet每列的最大宽度*/
        const colWidth = data.map(row => row.map(val => {
            /*先判断是否为null/undefined*/
            if (val == null) {
                return {
                    'wch': 10
                };
            }
            /*再判断是否为中文*/
            else if (val.toString().charCodeAt(0) > 255) {
                return {
                    'wch': val.toString().length * 2
                };
            } else {
                return {
                    'wch': val.toString().length
                };
            }
        }))
        /*以第一行为初始值*/
        let result = colWidth[0];
        for (let i = 1; i < colWidth.length; i++) {
            for (let j = 0; j < colWidth[i].length; j++) {
                if (result[j]['wch'] < colWidth[i][j]['wch']) {
                    result[j]['wch'] = colWidth[i][j]['wch'];
                }
            }
        }
        ws['!cols'] = result;
    } else {
        let wchList = [];
        for (let item in ws) {
            if (item.substring(1, 2) == 1 && item.length == 2) {
                wchList.push({ wch: autoWidth });
            }
        }
        //设置列宽
        ws["!cols"] = wchList;
    }

    /* add worksheet to workbook */
    wb.SheetNames.push(ws_name);
    wb.Sheets[ws_name] = ws;

    var wbout = XLSX.write(wb, {
        bookType: bookType,
        bookSST: false,
        type: 'binary',
        defaultCellStyle: defaultCellStyle
    });
    FileSaver.saveAs(new Blob([s2ab(wbout)], {
        type: "application/octet-stream"
    }), `${filename}.${bookType}`);
}


